package com.archermind.style.service;

import com.archermind.style.bean.User;
import com.feng.fengDUtil.BaseService;
import com.archermind.style.util.TreeUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Transactional
public class SceneService  extends BaseService {

    private static final Logger log = LoggerFactory.getLogger(SceneService.class);

    public String getSceneName(Integer sceneId){
        return sql("select text from scene where id = ?").one(String.class,sceneId);

    }

    public List<Map> getSceneTree() {
        String sql ="select * from scene order by id";
        List<Map> list = sql(sql).list(Map.class);
        return TreeUtil.geneTree(list);
    }

    public List<Map> getSceneTree(User user) {


        Set instanceIds = new HashSet();
        if(StringUtils.isNotEmpty(user.getReadInstanceIds())){
            instanceIds.addAll(Arrays.asList(user.getReadInstanceIds().split(",")));
        }
        if(StringUtils.isNotEmpty(user.getWriteInstanceIds())){
            instanceIds.addAll(Arrays.asList(user.getWriteInstanceIds().split(",")));
        }
        if(instanceIds.size()==0){
            return Collections.emptyList();
        }
        List<Map> allList = sql("select * from scene").list(Map.class);
        String sql = "select * from scene s where exists (select 1 from instance i where i.sceneId = s.id and i.id in ("+genePlaceHolders(instanceIds.size())+"))";
        List<Map> tarList = sql(sql).list(Map.class,instanceIds.toArray());

        TreeUtil.addParents(tarList,allList);
        return TreeUtil.geneTree(tarList);
    }
}
